from django.shortcuts import render, redirect, reverse
from django.views import View
from django import http
import re, json, logging
from django.db import DatabaseError
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from django.contrib.auth.mixins import LoginRequiredMixin

from users.models import User, Address
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from celery_tasks.email.tasks import send_verify_email
from users.utils import generate_email_verify_url, check_email_verify_url
from users import constants
from goods.models import SKU
from carts.utils import merge_cookie_to_redis
# Create your views here.


# 日志记录器
logger = logging.getLogger('django')

# 当某个视图需要限制用户访问，且返回html，我们使用LoginRequiredMixin来限制用户访问
# 当某个视图需要限制用户访问，且返回JSON，我们使用LoginRequiredJSONMixin来限制用户访问


class UserBrowseHistory(LoginRequiredJSONMixin, View):
    """用户浏览记录"""

    def post(self, request):
        """保存用户浏览记录"""
        # 接收参数：sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('参数sku_id错误')

        # 创建连接到redis的对象
        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 先去重
        # redis_conn.lrem('key', 0, '要添加的元素')
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 再添加
        # redis_conn.lpush('key', '要添加的元素')
        pl.lpush('history_%s' % user_id, sku_id)
        # 最后截取：截取最前面五个元素[0,1,2,3,4]
        # redis_conn.ltrim('key', '开始的角标', '结束的角标')
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 必须执行
        pl.execute()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self, request):
        """查询用户浏览记录"""
        # 创建连接到redis的对象
        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        # 读取redis中缓存的商品sku_id(浏览记录)
        # redis_conn.lrange('key', '开始角标', '结束的角标')
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)

        # 遍历出所有的sku_id,并查询出对应的sku信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image.url
            }
            skus.append(sku_dict)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': skus})


class AddressCreateView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """实现新增地址后端逻辑"""
        # 判断用户地址数量是否超过上限：最多20个(不包含已删除的)
        # count = Address.objects.filter(user=request.user, is_deleted=False).count()
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超出地址上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 保存地址数据
        try:
            address = Address.objects.create(
                user = request.user,
                title = receiver,
                receiver = receiver,
                # province = province, # 将省份模型对象赋值给province (province = Area.objects.get(id=province_id))
                province_id = province_id, # 省份ID赋值给外键
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email,
            )

            # 指定默认地址：如果用没有默认地址，那么在新增了地址之后，需要指定默认地址
            if not request.user.default_address:
                # request.user.default_address_id = address.id
                request.user.default_address = address
                request.user.save()
        except DatabaseError:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 封装新增的地址数据：为了新增地址成功后在页面直接刷新新的地址
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})


class AddressView(LoginRequiredMixin, View):
    """收货地址"""

    def get(self, request):
        """提供收货地址页面"""
        # 查询当前登录用户未被逻辑删除的地址
        addresses = request.user.addresses.filter(is_deleted=False)

        # 将addresses模型列表转字典列表：方便VUE将它解析成为JSON数据渲染页面
        address_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_list.append(address_dict)

        # 构造上下文
        context = {
            'addresses': address_list,
            # 'default_address_id': request.user.default_address.id # 必须保证一定有默认地址才能这么读取数据
            'default_address_id': request.user.default_address_id # 更加安全的，无论是否有默认地址都不会错
        }

        # 渲染收货地址页面
        return render(request, 'user_center_site.html', context)


class VerifyEmailView(View):
    """验证用户邮箱"""

    def get(self, request):
        """实现验证用户邮箱逻辑"""
        # 接收参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.HttpResponseForbidden('缺少token')

        # 提取要验证邮箱的用户
        user = check_email_verify_url(token)
        if not user:
            return http.HttpResponseForbidden('验证链接失效')

        # 将该用户的email_active字段设置为True
        try:
            user.email_active = True
            user.save()
        except DatabaseError:
            return http.HttpResponseServerError('验证邮箱失败')

        # 响应结果：重定向到用户中心
        return redirect(reverse('users:info'))


class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接收参数:获取请求体中的JSON
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        email = json_dict.get('email')

        # 校验参数
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')

        # 保存邮箱
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.EMAILERR, 'errmsg': '添加邮箱失败'})

        # 异步发送验证邮件
        verify_url = generate_email_verify_url(request.user)
        send_verify_email.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        """提供用户中心页面"""
        # 只有前面判断了用户是已登录的用户，我们才能够使用request.user获取当前登录用户对象
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        return render(request, 'user_center_info.html', context)


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录的逻辑"""
        # 清理状态保持信息
        logout(request)

        # 创建响应对象
        response = redirect(reverse('contents:index'))

        # 清理写入到cookie中的用户名
        response.delete_cookie('username')

        # 响应结果：重定向到首页
        return response


class LoginView(View):
    """用户名登录"""

    def get(self, request):
        """提供用户登录页面"""
        return render(request, 'login.html')

    def post(self, request):
        """实现登录逻辑"""
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 校验参数
        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或手机号')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 认证用户：本质就是使用用户名和密码去查询用户是否存在
        user = authenticate(request=request, username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '登录失败'})

        # 状态保持
        login(request, user)

        # 记住登录
        if not remembered:
            # 不记住登录:状态保持信息在会话结束后就销毁
            request.session.set_expiry(0)
        else:
            # 记住登录：状态保持时长为两周
            request.session.set_expiry(None) # 如果参数为None默认两周

        # 获取next参数
        next = request.GET.get('next')
        # 判断登录地址中是否有next参数
        if not next:
            # 创建响应对象
            response = redirect(reverse('contents:index'))
        else:
            response = redirect(next)

        # 将用户名写入到cookie
        # response.set_cookie('key', 'value', '过期时间')
        response.set_cookie('username', user.username, expires=3600*24*14)

        # 登录成功后，合并购物车
        response = merge_cookie_to_redis(request=request, user=user, response=response)

        # 响应结果
        return response


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        """
        查询指定用户记录个数
        :param username: 用户名
        :return: JSON
        """
        # 查询指定用户记录个数:filter()返回的是查询集QuerySet([User,User])
        count = User.objects.filter(username=username).count()
        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    """用户注册"""

    def get(self, request):
        """提供用户注册页面"""
        return render(request, 'register.html')

    def post(self, request):
        """实现用户注册逻辑"""
        # 接收参数:不同的发送参数的方式，决定了不同的取参数的方式
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code_client = request.POST.get('sms_code')
        allow = request.POST.get('allow')

        # 校验参数：首先判断必传参数是否缺少，然后以取反的方式依次校验参数
        # all()如果发现列表中有任意一个元素为空就返回False。反之，返回True
        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('参数username错误')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 补充短信验证
        # 从redis读取短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'register.html', {'sms_code_errmsg': '短信验证码失效'})
        # 对比短信验证码
        sms_code_server = sms_code_server.decode()
        if sms_code_client != sms_code_server:
            return render(request, 'register.html', {'sms_code_errmsg': '短信验证码有误'})

        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 保存用户注册数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 状态保持:如果成功就表示用户登入到美多商城
        login(request, user)

        # 创建响应对象
        response = redirect(reverse('contents:index'))

        # 将用户名写入到cookie
        # response.set_cookie('key', 'value', '过期时间')
        response.set_cookie('username', user.username, expires=3600 * 24 * 14)

        # 响应注册结果:重定向到首页
        return response